﻿using System;
using System.Web.Mvc;
using Gfw.BLL.Basic.Stock;
using Gfw.Infrastructure.ExceptionImpl;
using Gfw.Infrastructure.Stock.Enums;
using Gfw.Web.Models.Stock;
using System.Linq;

namespace Gfw.Web.Areas.Stock.Controllers
{
    public class AdminController : Controller
    {
        #region 管理帐户

        /// <summary>
        /// 管理帐户基本情况
        /// </summary>
        /// <returns></returns>
         [LAuthorize(RequireRole="Admin")]
        public ActionResult Index()
        {
            var model = UsAdminLogic.GetAccount();
            return View(model);
        }

        #endregion

        #region 电子股发行

        /// <summary>
        /// 创建电子股发行记录
        /// </summary>
        /// <returns></returns>
       [LAuthorize(RequireRole = "Admin")]
        public ActionResult CreateHistroy()
        {
            var list = UsAdminLogic.GetCreateHistories();
            return View(list);
        }

        [LAuthorize(RequireRole = "Admin")]
        public ActionResult Create()
        {
            return View();
        }

      [LAuthorize(RequireRole = "Admin")]
        [HttpPost]
        public ActionResult Create(CreateHistroyModel model)
        {
            try
            {
                if (model.WholesaleCount < 100000 || model.WholesaleCount%100000!=0)
                {
                    throw new Exception("创建股票应当以100000（十万）为基本单位");
                }
                model.Userid = L.Manage.Authentication.Context.CurrentUser.Id;
                model.UserLoginName = L.Manage.Authentication.Context.CurrentUser.LoginName;
                model.Id = Guid.NewGuid().ToString();
                model.WholesaleDate = DateTime.Now;
                UsAdminLogic.Create(model);
                return RedirectToAction("CreateHistroy");
            }
            catch (Exception exp)
            {
                ModelState.AddModelError("", exp.Message);
                return View();
            }
        }

        #endregion

        #region 股票交易
        #region 卖出股票
        [LAuthorize(RequireRole="Admin")]
        public ActionResult Sell(bool? done)
        {
            if (done.HasValue && done.Value && !Request.QueryString.AllKeys.Contains("done"))
                ViewBag.Done = true;
            var model = UsAdminLogic.GetSellModel();

            return View(model);
        }

        [LAuthorize(RequireRole="Admin")]
        [HttpPost]
        public ActionResult Sell(SellModel model)
        {
            try
            {
                if (model.SellCount <= 100)
                {
                    throw new Exception("卖出股票必须是100股的整数倍。");
                }
                UsAdminLogic.Sell(model, L.Manage.Authentication.Context.CurrentUser.Id);
                return RedirectToAction("Sell", new { done = true });
            }
            catch (Exception exp)
            {

                ModelState.AddModelError("", exp.Message);
                return View(model);
            }
        }
        #endregion

        #region 购入
        [LAuthorize(RequireRole="Admin")]
        public ActionResult Buy(bool? done)
        {
            if (done.HasValue && done.Value && !Request.QueryString.AllKeys.Contains("done"))
                ViewBag.Done = true;

            var model = UsAdminLogic.GetBuyModel();
            return View(model);
        }

        [LAuthorize(RequireRole="Admin")]
        [HttpPost]
        public ActionResult Buy(BuyModel model)
        {
            try
            {
                if (model.BuyCount < 100 || model.BuyCount % 100 != 0)
                {
                    throw new Exception("买入股票必须是100股的整数倍。");
                }
                UsAdminLogic.Buy(model, L.Manage.Authentication.Context.CurrentUser.Id);
                return RedirectToAction("Buy", new { done = true });
            }
            catch (Exception exp)
            {
                ModelState.AddModelError("", exp.Message);
                return View(model);
            }
        }
        #endregion
        #endregion

        #region 股票市场管理

        [LAuthorize(RequireRole="Admin")]
        public ActionResult ManageMarket()
        {
            var state = UsAdminLogic.GetMarketRunnintState();
            return View(state);
        }

        [LAuthorize(RequireRole="Admin")]
        [HttpPost]
        public ActionResult ManageMarket(int newstate)
        {
            try
            {
                var state = (MarketRunningStateEnum)Enum.ToObject(typeof(MarketRunningStateEnum), newstate);
                UsAdminLogic.SetMarketRunningState(state);
                return RedirectToAction("ManageMarket");
            }
            catch (Exception exp)
            {
                ModelState.AddModelError("", exp.Message);
                var state = UsAdminLogic.GetMarketRunnintState();
                return View(state);
            }
        }
        
        #endregion

        #region 股票拆分
        public ActionResult Split()
        {
            SplitModel model = new SplitModel()
                                   {
                                       CurrentPrice = StockManager.CurrentPrice,
                                       Multiple = 2
                                   };
            return View(model);
        }

        [HttpPost]
        public ActionResult Split(SplitModel model)
        {
            try
            {
                if (model.Multiple <= 1)
                    throw new Exception("倍数格式不正确。倍数应当大于或等于2。");
                if (StockManager.ServcieIsRunning())
                    throw new Exception("交易服务正在运行，不能执行拆分。强行拆分，将导致股票价格混乱。");
                UsAdminLogic.MarketSplit(model.Multiple);
                return RedirectToAction("SplitResult");
            }
            catch(Exception exp)
            {
                ModelState.AddModelError("", exp.Message);
                return View(model);
            }
        }

        public ActionResult SplitResult()
        {
            return View();
        }
        #endregion

    }
}
